//
//  EmoticonViewController.swift
//  Super_WeiBo
//
//  Created by SuperMac on 16/5/9.
//  Copyright © 2016年 lc. All rights reserved.
//

import UIKit

private let LCEmoticonCellReuseIdentifier = "LCEmoticonReuseIdentifier"

class EmoticonViewController: UIViewController
{
    // 定义一个闭包属性，用于传递表情模型
    var emoticonDidSelectedCallVack:(emoticon: Emoticon)->()
    
    init(callBack: (emoticon: Emoticon)->())
    {
        emoticonDidSelectedCallVack = callBack
        super.init(nibName: nil, bundle: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.cyanColor()
        
        // 初始化UI
        setupUI()
    }
    
    private func setupUI()
    {
        // 添加子控件 
        view.addSubview(collectionView)
        view.addSubview(toolbar)
        
        // 布局子控件
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        
        var cons = [NSLayoutConstraint]()
        let dict = ["collectionView": collectionView, "toolbar": toolbar]
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolbar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-[toolbar(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
        view.addConstraints(cons)
    }
    
    /**
     响应toolBar点击事件
     */
    func itemClick(item: AnyObject)
    {
        collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: item.tag), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
    
    // MARK: - 懒加载
    private lazy var collectionView: UICollectionView = {
       let c = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonLayout())
        c.dataSource = self
        c.delegate = self
        // 注册cell
        c.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: LCEmoticonCellReuseIdentifier)
        return c
    }()

    
    private lazy var toolbar: UIToolbar = {
       let bar = UIToolbar()
        var items = [UIBarButtonItem]()
        bar.tintColor = UIColor.darkGrayColor()
        let b = UIBarButtonItem()
        
        var index = 0
        for title in ["最近","默认","emoji","浪小花"]
        {
            let item = UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(EmoticonViewController.itemClick(_:)))
            item.tag = index++
            items.append(item)
            
            // 添加btn间隙
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        // 移除最后一个间隙
        items.removeLast()
        bar.items = items
        return bar
    }()

    private lazy var packages: [EmoticonPackage] = EmoticonPackage.packageList
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
extension EmoticonViewController: UICollectionViewDataSource,UICollectionViewDelegate
{
    // 有多少组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    // 每组多少行
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons?.count ?? 0
    }
    // 每行展示内容
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LCEmoticonCellReuseIdentifier, forIndexPath: indexPath) as! EmoticonCell
        cell.backgroundColor = UIColor.cyanColor()
        cell.backgroundColor = (indexPath.row % 2 == 0) ? UIColor.redColor() : UIColor.cyanColor()
        
        let package = packages[indexPath.section]
        cell.emoticon = package.emoticons![indexPath.item]
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let emoticon = packages[indexPath.section].emoticons![indexPath.item]
        // 处理最近表情
        emoticon.times++ // 使用次数+1
        packages[0].appendEmoticons(emoticon)
        // 通过闭包回调通知当前点击了哪个表情
        emoticonDidSelectedCallVack(emoticon: emoticon)
        // 点击次数改变后要重新刷新一次UI
        collectionView.reloadSections(NSIndexSet(index: 0))
    }
}

class EmoticonCell: UICollectionViewCell {
    var emoticon: Emoticon?
    {
        didSet{
            // 1、判断是否未图片表情
            if emoticon!.chs != nil
            {
                iconBtn.setImage(UIImage(contentsOfFile: emoticon!.imagePath!), forState: UIControlState.Normal)
            }
            else
            {
                iconBtn.setImage(nil, forState: UIControlState.Normal)
            }
            
            // 2、emoji表情（加上??可以防止重用）
            iconBtn.setTitle(emoticon!.emojiStr ?? "", forState: UIControlState.Normal)
            
            // 3、判断是否是删除按钮
            if emoticon!.isRemoveButton
            {
                iconBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                iconBtn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    private func setupUI()
    {
        contentView.addSubview(iconBtn)
        iconBtn.backgroundColor = UIColor.brownColor()
        iconBtn.frame = CGRectInset(contentView.bounds, 4, 4)
        iconBtn.userInteractionEnabled = false
    }
    // MARK: - 懒加载
    private lazy var iconBtn: UIButton = {
       let b  = UIButton()
        b.titleLabel?.font = UIFont.systemFontOfSize(32)
        return b
    }()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

/// 自定义布局
class EmoticonLayout: UICollectionViewFlowLayout
{
    override func prepareLayout() {
        super.prepareLayout()
        
        // 设置cell相关属性
        let width = (collectionView?.bounds.width)! / 7
        itemSize = CGSize(width: width, height: width)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        // 设置colltionView
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
        
        // 最好不要乘以0.5，因为CGFloat不准确，所以如果乘以0.5在 iPhone4或4s上会有问题
        let y = (collectionView!.bounds.height - 3*width) * 0.5
        collectionView?.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
    }
}




